package top.lidee.module.schedule.twice.management;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import top.lidee.common.bean.WxPayV3Bean;
import top.lidee.common.service.twice.management.MtStoreWechatInputPieceAccountValidationService;
import top.lidee.common.service.twice.management.MtStoreWechatInputPieceAuditDetailService;
import top.lidee.common.service.twice.management.MtStoreWechatInputPieceLogService;
import top.lidee.common.service.twice.third.wechat.WechatPayJJCommonService;
import top.lidee.common.to.wx.Audit_detail;
import top.lidee.common.to.wx.WxSelectIncomingPartsTo;
import top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceAccountValidationEntity;
import top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceAuditDetailEntity;
import top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceLogEntity;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

import static top.lidee.framework.constant.WechatConstant.*;

/**
 * @author 张一恒
 * @version 1.0
 * @description: 微信收款 平台收付通 查询申请状态API
 * @date 2024/10/8 16:27
 */
@Component
@Slf4j
public class WechatPaySftSelectJob {

    @Autowired
    private WxPayV3Bean wxPayV3Bean;

    @Autowired
    private MtStoreWechatInputPieceLogService mtStoreWechatInputPieceLogService;

    @Autowired
    private MtStoreWechatInputPieceAccountValidationService mtStoreWechatInputPieceAccountValidationService;

    @Autowired
    private MtStoreWechatInputPieceAuditDetailService mtStoreWechatInputPieceAuditDetailService;

    @Autowired
    private WechatPayJJCommonService wechatPayJJCommonService;

    /**
     * @return void
     * @description 查询申请状态API
     * 定时查询收付通日志表，进件中的
     * 申请状态
     * 枚举值：
     * CHECKING：资料校验中
     * ACCOUNT_NEED_VERIFY：待账户验证
     * AUDITING：审核中
     * REJECTED：已驳回
     * NEED_SIGN：待签约
     * FINISH：完成
     * FROZEN：已冻结
     * CANCELED：已作废
     * @author zhangyiheng
     * @date 2024/10/8 16:32
     */
//    @Scheduled
    @Transactional
    public void sftCheckApplicationStatus() {
        log.info("=============微信收付通查询申请状态API Start=============");
        //查询收付通日志表
        List<MtStoreWechatInputPieceLogEntity> listed = mtStoreWechatInputPieceLogService.list(Wrappers.<MtStoreWechatInputPieceLogEntity>lambdaQuery()
                .eq(MtStoreWechatInputPieceLogEntity::getState, IN_THE_INCOMING));

        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger failedCount = new AtomicInteger(0);
        AtomicInteger resFailedCount = new AtomicInteger(0);
        Optional.ofNullable(listed).ifPresent(item -> {

            for (MtStoreWechatInputPieceLogEntity pieceLog : item) {
                //优先使用申请单号查询
                String url = "";
                if (Objects.nonNull(pieceLog.getApplymentId())) {
                    url = wxPayV3Bean.getApplymentIdUrl() + pieceLog.getApplymentId();
                } else {
                    url = wxPayV3Bean.getOutRequestNoUrl() + pieceLog.getOutRequestNo();
                }

                Map<String, Object> map = wechatPayJJCommonService.pushRequestOfGetApply(url, "收付通");
                String res = (String) map.get("res");
                int code = (int) map.get("code");

                if (Objects.equals(code, 200)) {
                    WxSelectIncomingPartsTo to = JSON.parseObject(res, WxSelectIncomingPartsTo.class);

                    MtStoreWechatInputPieceLogEntity logEntity = getMtStoreWechatInputPieceLogEntity(pieceLog, to, code, successCount);

                    //保存汇款账户验证信息
                    saveTheRemittanceAccount(pieceLog, to, logEntity);

                    //保存收付通进件日志
                    mtStoreWechatInputPieceLogService.saveOrUpdate(logEntity);

                    //保存收付通驳回原因详情
                    saveTheReasonForTheRejection(pieceLog, to, failedCount);
                    log.info("=============微信收付通查询申请状态API 处理成功，店铺id：{}=============", pieceLog.getStoreId());
                } else {
                    resFailedCount.incrementAndGet();
                }

            }
        });

        log.debug("=====微信收付通查询申请状态API 审核成功:{},审核失败:{},请求失败:{}=====,", successCount.get(), failedCount.get(), resFailedCount.get());
        log.info("=============微信收付通查询申请状态API End=============");
    }

    /**
     * @param pieceLog
     * @param to
     * @param code
     * @return top.lidee.repository.model.twice.pojo.management.MtStoreWechatInputPieceLogEntity
     * @description 组装查询申请状态API 基本参数
     * @author zhangyiheng
     * @date 2024/10/9 18:09
     */
    private MtStoreWechatInputPieceLogEntity getMtStoreWechatInputPieceLogEntity(MtStoreWechatInputPieceLogEntity pieceLog, WxSelectIncomingPartsTo to, int code, AtomicInteger successCount) {
        MtStoreWechatInputPieceLogEntity logEntity = new MtStoreWechatInputPieceLogEntity();
        logEntity.setApplymentId(Long.valueOf(to.getApplyment_id()));
        logEntity.setOutRequestNo(to.getOut_request_no());
        logEntity.setStatusCode(code);
        logEntity.setStoreId(pieceLog.getStoreId());
        String applymentState = to.getApplyment_state();
        switch (applymentState) {
            case CHECKING:
            case ACCOUNT_NEED_VERIFY:
            case AUDITING:
            case NEED_SIGN:
                logEntity.setState(IN_THE_INCOMING);
                break;
            case FINISH:
                logEntity.setState(THE_INCOMING_REVIEW_IS_COMPLETE);
                break;
            case REJECTED:
            case FROZEN:
            case CANCELED:
                logEntity.setState(INCOMING_ITEMS_ARE_ABNORMAL);
                break;
            default:
                break;
        }
        logEntity.setApplymentState(applymentState);
        logEntity.setApplymentStateDesc(to.getApplyment_state_desc());
        logEntity.setSignState(to.getSign_state());
        logEntity.setSignUrl(to.getSign_url());
        logEntity.setSubMchid(to.getSub_mchid());
        logEntity.setLegalValidationUrl(to.getLegal_validation_url());
        return logEntity;
    }

    /**
     * @param pieceLog
     * @param to
     * @return void
     * @description 驳回原因详情    audit_detail 	array 	否
     * 各项资料的审核情况。当申请状态为REJECTED或 FROZEN时才返回。
     * @author zhangyiheng
     * @date 2024/10/9 18:07
     */
    private void saveTheReasonForTheRejection(MtStoreWechatInputPieceLogEntity pieceLog, WxSelectIncomingPartsTo to, AtomicInteger failedCount) {
        Optional.ofNullable(to.getAudit_detail()).ifPresent(auditDetails -> {
            List<MtStoreWechatInputPieceAuditDetailEntity> detailEntities = new ArrayList<>();
            for (Audit_detail auditDetail : auditDetails) {
                MtStoreWechatInputPieceAuditDetailEntity detail = new MtStoreWechatInputPieceAuditDetailEntity();

                detail.setParamName(auditDetail.getParam_name());
                detail.setRejectReason(auditDetail.getReject_reason());
                detail.setWechatInputPieceId(pieceLog.getId());
                detailEntities.add(detail);
            }
            mtStoreWechatInputPieceAuditDetailService.saveBatch(detailEntities);
            failedCount.incrementAndGet();
        });
    }

    /**
     * @param pieceLog
     * @param to
     * @param logEntity
     * @return void
     * @description 汇款账户验证信息    account_validation 	object 	否
     * 当申请状态为ACCOUNT_NEED_VERIFY 时有返回，可根据指引汇款，完成账户验证。
     * @author zhangyiheng
     * @date 2024/10/9 18:06
     */
    private void saveTheRemittanceAccount(MtStoreWechatInputPieceLogEntity pieceLog, WxSelectIncomingPartsTo to, MtStoreWechatInputPieceLogEntity logEntity) {
        MtStoreWechatInputPieceAccountValidationEntity accountValidationEntity = new MtStoreWechatInputPieceAccountValidationEntity();
        Optional.ofNullable(to.getAccount_validation()).ifPresent(accountValidation -> {
            accountValidationEntity.setAccountName(accountValidation.getAccount_name());
            accountValidationEntity.setAccountNo(accountValidation.getAccount_no());
            accountValidationEntity.setPayAmount(accountValidation.getPay_amount());
            accountValidationEntity.setDestinationAccountNumber(accountValidation.getDestination_account_number());
            accountValidationEntity.setDestinationAccountName(accountValidation.getDestination_account_name());
            accountValidationEntity.setDestinationAccountBank(accountValidation.getDestination_account_bank()
            );
            accountValidationEntity.setCity(accountValidation.getCity());
            accountValidationEntity.setRemark(accountValidation.getRemark());
            accountValidationEntity.setDeadline(accountValidation.getDeadline());
            accountValidationEntity.setWechatInputPieceId(pieceLog.getId());
            mtStoreWechatInputPieceAccountValidationService.save(accountValidationEntity);

            logEntity.setAccountValidationId(accountValidationEntity.getId());
        });
    }


}
